<?php
/**
 * 客户逻辑类
 *
 */

namespace app\crm\logic;

use app\crm\model\Customer;
use think\facade\Db;
use app\admin\model\User;

class CustomerLogic extends AbstractLogic
{
    /**
     * 获取员工角色ID
     *
     * @param $userId
     * @return array|false|string
     */
    public function getEmployeeGroups($userId)
    {
        return Db::name('admin_access')->where('user_id', $userId)->column('group_id');
    }

    /**
     * 获取员工角色下的规则ID
     *
     * @param $groupIds
     * @return array|false|string
     */
    public function getEmployeeRules($groupIds)
    {
        return Db::name('admin_group')->whereIn('id', $groupIds)->column('rules');
    }

    /**
     * 获取公海管理规则数据
     *
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPoolRules()
    {
        # 公海管理查询条件
        $poolRuleWhere['types'] = 2;
        $poolRuleWhere['title'] = '公海管理';
        $poolRuleWhere['name']  = 'customer';
        $poolRuleWhere['level'] = 2;

        # 查询公海管理ID
        $poolRuleId = Db::name('admin_rule')->where($poolRuleWhere)->value('id');

        return Db::name('admin_rule')->field(['id', 'name'])->where('pid', $poolRuleId)->select();
    }

    /**
     * 获取销售新增数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-06 9:28
     */
    public function getNewSalesData($userId,array $request): array
    {
        $data = [
            'name'      => '新增客户',
            'num'       => 0,
            'desc'      => '新增客户成交率',
            'value'     => 0
        ];
        $sqlWhere = '';
        if($request['start_time'] && $request['end_time']){
            $sqlWhere = append_where_sql($sqlWhere,"  create_time BETWEEN " . $request['start_time'] . " AND " . $request['end_time']);
        }
        $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'customer');
        if(in_array(-1,$dataAuthUid)){
            return $data;
        }
        $sqlWhere = !in_array('all',$dataAuthUid) ? append_where_sql($sqlWhere," trans_user_id IN (" . implode(',', $dataAuthUid) . ")") : $sqlWhere;
        $sqlWhere && $sqlWhere = ' where'.$sqlWhere;
        try {
            $sql = "select count(1) new_quantity,sum( CASE WHEN status = 2 THEN 1 ELSE 0  END ) AS total_deal FROM shrimp_crm_customer".$sqlWhere;
            $data = \think\facade\Db::query($sql);
            $data = array_map('intval',$data[0]);
            $data['new_deal_rate'] = 0;
            $data['new_quantity'] && $data['new_deal_rate'] =  round($data['total_deal'] / $data['new_quantity'],4) * 100 .'%';
            unset($data['total_deal']);
            $data = [
                    'name'      => '新增客户',
                    'num'       => $data['new_quantity'],
                    'desc'      => '新增客户成交率',
                    'value'     => $data['new_deal_rate']
            ];

        } catch (\Exception $e) {
        }
        return $data;
    }


    /**
     * 获取汇总数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-06 14:23
     */
    public function getSummaryData($userId,array $request): array
    {
        $data = [
            [
                'name'      => '总计',
                'value'     => 0,
            ],
            [
                'name'      => '待处理',
                'value'     => 0,
            ],
            [
                'name'      => '已成交',
                'value'     => 0,
            ],
            [
                'name'      => '未成交',
                'value'     => 0,
            ],
        ];
        $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'customer');
        if(in_array(-1,$dataAuthUid)){
            return $data;
        }
        $uidSql = !in_array('all',$dataAuthUid) ? "where trans_user_id IN (" . implode(',', $dataAuthUid) . ")" : '';
        try {
            $sql = "select count(1) total_quantity,sum( CASE WHEN status = 1 THEN 1 ELSE 0  END ) AS total_pending_quantity,sum( CASE WHEN status = 2 THEN 1 ELSE 0  END ) AS total_deal_quantity,sum( CASE WHEN status = 3 THEN 1 ELSE 0  END ) AS total_no_deal_quantity FROM shrimp_crm_customer ".$uidSql  ;
            $data = Db::query($sql);
            $data = array_map('intval',$data[0]);
            $data = [
                [
                    'name'      => '总计',
                    'value'       => $data['total_quantity'],
                ],
                [
                    'name'      => '待处理',
                    'value'       => $data['total_pending_quantity'],
                ],
                [
                    'name'      => '已成交',
                    'value'       => $data['total_deal_quantity'],
                ],
                [
                    'name'      => '未成交',
                    'value'       => $data['total_no_deal_quantity'],
                ],
            ];

        } catch (\Exception $e) {
        }
        return $data;

    }

    /**
     * 获取消息的条件
     * @param $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-12 14:15
     */
    protected function getMessageWhere($request)
    {
       $map = [
            ['trans_time','>=',strtotime(date('Y-m-d') .' 00:00:00')],
            ['trans_time','<=',strtotime(date('Y-m-d') .' 23:59:59')]
        ];
       return $map;
    }

    /**
     * 今日分配的客户数量
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 14:55
     */
    public function getMessageNum($userId,array $request): int
    {
        $count = 0;
        $map = $this->getMessageWhere($request);
        try {
            // 获取数据权限UID范围
            $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'customer');

            $count = Customer::where($map)->when(!in_array('all', $dataAuthUid), function($query) use ($dataAuthUid) {
                    // 非超级管理员数据权限
                    $query->where(function($query) use ($dataAuthUid) {
                        $query->where('trans_user_id', 'in', $dataAuthUid);
                    });
                })->field('customer_id')->count();

        }catch (\Exception $e) {
        }
        return $count;


    }

    /**
     * 获取消息列表
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 15:40
     */
    public function getMessageList($userId,array $request): array
    {

        $statusName = [1=> '待处理', 2=> '已成交', 3=> '未成交'];
        $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'customer');
        $map = $this->getMessageWhere($request);
        $field = ['customer_id', 'name', 'status', 'level', 'city_level',  'source', 'telephone', 'province_id', 'city_id', 'is_auth',
            'district_id','remark', 'create_user_id', 'owner_user_id', 'trans_user_id', 'address', 'detail_address', 'last_time', 'create_time', 'update_time','trans_time','deal_time'];
        $order = 'customer.customer_id desc, customer.update_time desc';

        $queryTable = Customer::where($map)->alias('customer')

            ->when(!in_array('all', $dataAuthUid), function($query) use ($dataAuthUid) {
                    // 非超级管理员数据权限
                    $query->where(function($query) use ($dataAuthUid) {
                        $query->where('trans_user_id', 'in', $dataAuthUid);
                    });
                });
        $dataCount = $queryTable->count('customer_id');
        $list = $queryTable->when(!(isset($request['no_page']) && $request['no_page']), function ($query) use ($request) {
            $page = isset($request['page']) ? $request['page'] : 1;
            $limit = isset($request['limit']) ? $request['limit'] : 15;
            $query->limit(($page - 1) * $limit, $limit); // 分页
        })->field($field)->orderRaw($order)->select()->toArray();
        if($list){
            foreach ($list as &$value) {
                $province = Db::name('shop_region')->where('id', $value['province_id'])->value('name') ?? '';
                $city = Db::name('shop_region')->where('id', $value['city_id'])->value('name') ?? '';
                $district = Db::name('shop_region')->where('id', $value['district_id'])->value('name') ?? '';
                $value['address'] = $province.$city.$district;
                $value['owner_user_name'] = isset($value['owner_user_id']) && $value['owner_user_id'] ? User::where('id', $value['owner_user_id'])->value('realname'): '';
                $value['trans_user_name'] = isset($value['trans_user_id']) && $value['trans_user_id'] ? User::where('id', $value['trans_user_id'])->value('realname'): '';
                //$value["create_time"] = isset($value['create_time']) && $value['create_time'] ? date('Y-m-d H:i:s', $value['create_time']) : '';
                $value["last_time"] = isset($value['last_time']) && $value['last_time'] ? date('Y-m-d H:i:s', $value['last_time']) : '';
                //$value["update_time"] = isset($value['update_time']) && $value['update_time'] ? date('Y-m-d H:i:s', $value['update_time']) : '';
                $value["trans_time"] = isset($value['trans_time']) && $value['trans_time'] ? date('Y-m-d H:i:s', $value['trans_time']) : '';
                $value["deal_time"] = isset($value['deal_time']) && $value['deal_time'] ? date('Y-m-d H:i:s', $value['deal_time']) : '';
                // 查询该客户最后一次的下单时间
                // 查询该客户最后一次的下单时间
                $orderLastTime = Db::name('shop_order')->where('uid', $value['customer_id'])->order('id desc')->value('create_time');
                $value['last_order_time'] = $orderLastTime ? date('Y-m-d H:i:s', $orderLastTime) : '';
                $value['status_name'] = $statusName[$value['status']] ?? '';
                $returnData[] = $value;
            }
        }

        $permission = get_user_permission_menu($userId,'customer_list_tag');
        $data = [];
        $data['menu_list'] = $permission ? $permission : [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }



}
